#'
#' @TODO 差异top差异基因表达热图
#' @title 差异top差异基因表达热图
#' @param SeuratObj  Seurat对象
#' @param DE_df findallmarkers 结果df
#' @param od 结果输出路劲
#' @param cols 细胞类型标注颜色
#' @param name 文件命名字段
#' @param w 宽
#' @param h 高
#' @export
#' @author *WYK*
scDE_Heat <- function(SeuratObj = scRNA_epi, DE_df = Epi_markers, 
                      od = file.path(out_home, "/out/SC2/scRNA_EPI/"), cols = NULL,
                      name = "Epi_DExprs_heatmap", w = 7.3, h = 5, top_n = 6) {
    library(scales)
    library(tidyverse)
    library(Seurat)

    if (!dir.exists(od)) {
        dir.create(od, recursive = T)
    } else {
        message(od, " is ready.")
    }

    heatmap_gene <- DE_df %>%
        dplyr::select(cluster, gene, avg_log2FC) %>%
        rownames_to_column("symbol") %>%
        dplyr::select(-symbol) %>%
        group_by(cluster) %>%
        top_n(n = top_n, wt = avg_log2FC) %>%
        pull(gene)
    # 上述基因的表达谱数据
    heatmap_AveE <- AverageExpression(SeuratObj, features = heatmap_gene, verbose = TRUE, assays = "RNA") %>% .$RNA
    # 自定义颜色
    library(scales)

    if (is.null(cols)) {
        colourCount <- length(levels(SeuratObj))
        celltype_colors <- scales::hue_pal()(colourCount)
    } else {
        colourCount <- length(levels(SeuratObj))
        if (length(colourCount) > length(cols)) {
            message("颜色数目不对, 停止分析")
            return()
        }
        celltype_colors <- cols[seq_len(colourCount)]
    }

    gene2cell <- rep(levels(SeuratObj), each = top_n)

    gene_name <- rownames(heatmap_AveE)
    dat1 <- as.data.frame(heatmap_AveE)
    rownames(dat1) <- NULL
    dat1[, "gene"] <- gene_name

    gene_name <- rownames(heatmap_AveE)
    dat <- dat1 %>%
        select(gene, everything()) %>%
        pivot_longer(cols = -gene, names_to = "cell", values_to = "exprs") %>%
        inner_join(data.frame("gene" = gene_name, "gene2cell" = gene2cell)) %>%
        mutate(
            gene = factor(gene, levels = gene_name),
            cell = factor(cell, levels = levels(SeuratObj)),
            gene2cell = factor(gene2cell, levels = levels(SeuratObj))
        )


    scaleExpres <- \(exprs){
        exprs_scaled <- scale(exprs, center = T, scale = T) %>% as.numeric()
        return(exprs_scaled)
    }
    dat <- dat %>%
        group_by(gene) %>%
        mutate(exprs = scaleExpres(exprs)) %>%
        ungroup()

    p <- dat %>%
        ggplot(aes(x = cell, y = gene)) +
        geom_tile(aes(fill = exprs)) +
        theme_bw(11) +
        scale_y_discrete(position = "right") +
        theme(
            axis.title.y = element_blank(),
            axis.title.x.bottom = element_blank(), panel.grid = element_blank(),
            axis.text = element_text(color = "black"),
            plot.background = element_rect(fill = NULL, inherit.blank = T),
            axis.text.x.bottom = element_text(angle = 90,hjust = 1,vjust = .5,colour = celltype_colors),
            legend.position = "right", axis.ticks.x.bottom = element_blank()
        ) +
        scale_fill_gradient(
            low = muted("purple"),
            high = ("yellow"), name = "Scaled Exp"
        )  +
        coord_cartesian(clip = "off")

    # library(jjAnno)
    # P2 <- annoSegment(
    #     object = p,
    #     annoPos = "top",
    #     aesGroup = T,
    #     aesGroName = "cell",
    #     yPosition = length(unique(dat$gene)) + .7,
    #     segWidth = 1,
    #     addText = T,
    #     textRot = 30,
    #     textHVjust = c(.5),
    #     hjust = 0,
    #     # vjust = -2,
    #     textSize = 11,
    #     pCol = celltype_colors,
    #     textCol = celltype_colors
    # )
    plotout(p = p, od = od, name = name, w = w, h = h)

    return(p)
}
